import random
import subprocess
import time
from functools import partial

from loguru import logger

subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")  # 消除window下subprocess中文乱码问题
import execjs
execjs.eval("console.log('占位符')")
from apps.pdd.pdd.mms.mms_cert import MmsCertificate
from apps.pdd.pdd.mms.mms_search import MmsSearch


class MmsMain:

    def __init__(self, cookies=None):
        self.mms_search = MmsSearch(cookies)
        self.mms_certificate = MmsCertificate(cookies)

    def get_new_mall_name(self, mall_id):
        sql = (
            f"select shop_name, mall_logo from source_net_pdd_shop_info where mall_id = '{mall_id}' order by version desc limit 1"
        )
        datas = self.mms_certificate.to_db.find(sql, to_json=True)
        if datas:
            return datas[0]["shop_name"], datas[0]["mall_logo"]
        else:
            sql = f"select shop_name from zm_pdd_mall_id where mall_id = '{mall_id}' order by version desc limit 1"
            datas = self.mms_certificate.to_db.find(sql, to_json=True)
            if datas:
                return datas[0]["shop_name"], None
        return None, None

    def run(self, mall_id=None, mall_name=None):
        logger.info(f"开始查询 mall_id:{mall_id or ''} mall_name:{mall_name or ''}")
        if mall_id:
            new_mall_name, mall_logo = self.get_new_mall_name(mall_id)
            if new_mall_name:
                item = self.mms_search.mall_search_with_save(new_mall_name, mall_id)
                if item:
                    self.mms_certificate.run(item["mallIdEncrypt"], mall_id=mall_id)
            else:
                logger.error(f"{mall_id} 店铺名未找到")

        else:
            if mall_name:
                item = self.mms_search.mall_search(mall_name)
                if item:
                    self.mms_certificate.query_mall_licence_certificate(item["mallIdEncrypt"])
            else:
                logger.error("请输入店铺名或者mall_id")

    def auto_run_searched(self, size=100):
        for _ in range(size):
            sql = r"select mall_id, mall_id_encrypt from zm_pdd_mall_id where zm_certificate_flag = 1 and is_certificated is null and is_searched = 1 limit 1"
            datas = self.mms_certificate.to_db.find(sql, to_json=True)
            if datas:
                for data in datas:
                    if data['mall_id_encrypt']:
                        self.mms_certificate.run(data["mall_id_encrypt"], mall_id=data['mall_id'])
                    else:
                        self.run(data["mall_id"])
                    time.sleep(random.randint(10, 20))
        print("完成")

    def auto_run(self, size=100):
        for _ in range(size):
            sql = r"select mall_id from zm_pdd_mall_id where zm_certificate_flag = 1 and certificate_flag is null and shop_name not like '%\_%' and is_searched is null limit 1"
            datas = self.mms_certificate.to_db.find(sql, to_json=True)
            if datas:
                for data in datas:
                    self.run(data["mall_id"])
                    time.sleep(random.randint(10, 60))
        print("完成")


if __name__ == "__main__":
    cookies = {
        "PASS_ID": "1-kKGl5XhCnkT2BdI9ZvT5f5NTM2LSkUx6Jn0/Sj3zehmr7aENS0/Ex59hYy6a+Mwgvee4FOUIY9TUMkntgNEASw_380219423_170065474",
        "SUB_PASS_ID": "eyJ0IjoiY1QwTDdVTXhwWHBTZWlVNUxMaC9UeE9FRUNmUHc2VXF6eGxmWW5YWkZPY1B0dDRIZHZJZkRPd2tnS2RnNGVWWSIsInYiOjEsInMiOjE0LCJtIjozODAyMTk0MjMsInUiOjE3MDA2NTQ3NH0",
        # "PASS_ID": "1-2K7TNBf0ZT8sAckHqBI52QTdiiFAmlwDPLsV3u1G9nr08cRWNXdSmO/rzQihxyg2SVQUoY/gyu0YuOxDbB4fSw_239737279_170063703",
        # # "VISITOR_PASS_ID": "zjBUTyTpRdgsCBia5ScbinF8DEzfoPNRo5anD7QrZ7IxgPegnRuCSOaAqVa7k9xvuX8f7xBUHv1UuMAExDGEXfd1hUeETNEPwPSNtsL1360_103edfe74db",
        # # "SUB_PASS_ID": "eyJ0IjoiSDVGWTByVzlpMmx5UWxQS2hTYjAzRUNYRTlvNG8xbGhnRWZ2RDdybTlMZG1yWGpuVVN5RGUxWThBUXhrVzBwWiIsInYiOjEsInMiOjE0LCJtIjo3MDQ3ODUxODcsInUiOjE2MDc2MDA5MX0",
        # # "VISITOR_PASS_ID": "zjBUTyTpRdgsCBia5ScbinF8DEzfoPNRo5anD7QrZ7Krz4MntPdUBJ0QtVyE3zcFQRqRgDOxe7SFIsG_7r8pzYzL5KhQ3mININTY-j8fzVY_103edfe74db",
        # "SUB_PASS_ID": "eyJ0IjoieWVDUm4vSmh1UmNSV0xYM1RiNmtwSnpoc01FbnBlWHZheFBCMndmdXpHY0dZLzRrdTI1c0hDVnJPNVE3N3NIcCIsInYiOjEsInMiOjE0LCJtIjoyMzk3MzcyNzksInUiOjE3MDA2MzcwM30",
        # "PASS_ID": "1-QLLfr9l+Q/Y3oOyWoNeDtrhKboulTtS5NefHCvk6NImraFPct5oGf6omcjAmUGQDlpCHDYhgHXVlwRF4pDfatA_841582989_170064121",
        # "SUB_PASS_ID": "eyJ0IjoiR2FjK25qTFh4N3JGYWxZc01xSGVULzRuOExtbjJDM0JlWnZvYmFSRkJzWSszWGZudVB6TkpHMldlL2dJZG5mdyIsInYiOjEsInMiOjE0LCJtIjo4NDE1ODI5ODksInUiOjE3MDA2NDEyMX0",
    }

    # MmsMain(cookies).run(mall_id="102038163")

    # MmsMain(cookies).auto_run(50)
    MmsMain(cookies).auto_run_searched(8)
